#!/usr/bin/env python
# -*- coding: utf-8 -*-

import threading
import traceback
from utils.log import logger
from dispatcher import TestPreDispatcher,\
    TestPostDispatcher, TestRunDispatcher, TestProgressDispatcher


class TestFlow(object):
    def __init__(self, config):
        """
        init test flow
        """
        logger.debug("Test init")
        self.config = config

    def __enter__(self):
        logger.debug("Test __enter__")
        self.setup()
        return self

    def __exit__(self, _exc_type, _exc_value, _traceback):
        logger.debug("Test __exit__")
        self.cleanup()

    def setup(self):
        """
        setup the env for test
        """
        logger.debug("Test setup")
        dispatcher = TestPreDispatcher()
        dispatcher.map_method('run', self)

    def cleanup(self):
        """
        cleanup the env
        """
        logger.debug("Test cleanup")
        dispatcher = TestPostDispatcher()
        dispatcher.map_method('run', self)

    def _set_monitor(self):
        interval = self.config['testinfo'].get('test_monitor_interval', None)
        if interval:
            logger.debug("***Set monitor")
            dispatcher = TestProgressDispatcher()

            class Monitor:
                timer = None

                def start(self):
                    logger.debug("*** Timer worked **{}*".format(interval))
                    logger.debug('current threads count: {}'.format(threading.activeCount()))
                    dispatcher.map_method('run', self)
                    self.timer = threading.Timer(interval, self.start)
                    self.timer.start()

                def cancel(self):
                    self.timer.cancel()
            timer = Monitor()

            self.config['testinfo']['test_monitor_timer'] = timer

    def run(self):
        logger.debug("Test run ....")
        dispatcher = TestRunDispatcher()
        try:
            dispatcher.map_method('run', self)
        except Exception as e:
            logger.debug("-------------------------------")
            raise BaseException("{}\n{}".format(e, traceback.format_exc()))
